package io.github.rascaler.dcenter.controller;
import io.github.rascaler.dcenter.constant.ConstantItem;
import io.github.rascaler.dcenter.platforms.DbMapper;
import io.github.rascaler.dcenter.platforms.Parser;
import io.github.rascaler.dcenter.platforms.binance.BinanceCandlestickParser;
import io.github.rascaler.dcenter.platforms.binance.BinanceConstant;
import io.github.rascaler.dcenter.platforms.binance.BinanceFrequency;
import io.github.rascaler.dcenter.platforms.binance.BinanceInstrumentParser;
import io.github.rascaler.dcenter.pojo.Instrument.Limit;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.binance.connector.futures.client.exceptions.BinanceClientException;
import com.binance.connector.futures.client.exceptions.BinanceConnectorException;
import com.binance.connector.futures.client.impl.UMFuturesClientImpl;
import com.binance.connector.futures.client.utils.ProxyAuth;
import io.github.rascaler.dcenter.annotation.OuterResponseBody;
import io.github.rascaler.dcenter.db.DbManager;
import io.github.rascaler.dcenter.message.BasicEcode;
import io.github.rascaler.dcenter.platforms.Frequency;
import io.github.rascaler.dcenter.pojo.*;
import io.github.rascaler.dcenter.properties.BinanceProperties;
import io.github.rascaler.dcenter.properties.MemoryDBProperties;
import io.github.rascaler.dcenter.properties.ProxyInfo;
import io.github.rascaler.dcenter.properties.WebProperties;
import io.github.rascaler.dcenter.utils.DateUtil;
import io.github.rascaler.dcenter.ws.handler.KlineSubscribeMessageHandler;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import static io.github.rascaler.assertj.Assertions.assertThat;


/**
 * 订单查询
 */
@Slf4j
@Api(tags = "")
@Controller
@RequestMapping("memorydb")
public class MemoryController {

    @Autowired
    private DbManager dbManager;

    private final static ExecutorService pool = Executors.newFixedThreadPool(100);

//    public final static List<UMFuturesClientImpl> clients = new ArrayList<>();
    public final static UMFuturesClientImpl client = new UMFuturesClientImpl();


    public final static String[] frequencys = new String[] {"1min", "5min", "15min", "1hour", "4hour"};
//    public final static String[] frequencys = new String[] {"1min", "4hour"};

    private String keyTemplate = "binance:%s:%s:%s:%s";

    @Autowired
    private BinanceProperties binanceProperties;

    @Resource(type = BinanceCandlestickParser.class)
    private Parser binanceCandlestickParser;

    @Resource(type = BinanceInstrumentParser.class)
    private Parser binanceInstrumentParser;

    @Autowired
    private DbMapper dbMapper;

    public List<String> getNeedInitSymbols(String frequency) {
        List<String> needInitSymbols = new ArrayList<>();
        Map<String, Long> map = dbMapper.getTimeMap(frequency);
        Long today = DateUtil.today().getTime();
        dbManager.getMdb().getInstrumentMap().forEach((key, val) ->{
            Long dateTime = map.get(key);
            if (null == dateTime || dateTime < today) {
                needInitSymbols.add(val.getSymbol());
            }
        });
        return needInitSymbols;
    }


//    @ApiOperation("初始化")
//    @OuterResponseBody
//    @PostMapping("init")
//    public void init() {
//        // 初始化1440根bar，即使1天的数据
//        List<Future<String>> tasks = new ArrayList<>();
//        List<String> result = new ArrayList<>();
//
//        if (binanceProperties.getUseProxy()) {
//            // 设置代理
//            ProxyInfo proxySetting = binanceProperties.getProxies().get(0);
//            Proxy proxyConn = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxySetting.getHost(), proxySetting.getPort()));
//            ProxyAuth proxy = new ProxyAuth(proxyConn, null);
//            client.setProxy(proxy);
//        }
//
//        String instStr = client.market().exchangeInfo();
//        List<Instrument> instruments = binanceInstrumentParser.parse(instStr);
//        dbManager.getMdb().setInstrumentMap(instruments.stream().collect(Collectors.toMap(Instrument::getSymbol, i -> i)));
//        // bar
//        Arrays.stream(frequencys).forEach(f -> {
//            List<String> needInitSymbols = getNeedInitSymbols(f);
//            while (needInitSymbols.size() > 0) {
//                result.clear();
//                tasks.clear();
//                for (String symbol:needInitSymbols) {
//                    Future<String> future = pool.submit(() -> {
//                        LinkedHashMap<String, Object> parameters = new LinkedHashMap<>();
//                        parameters.put("symbol", symbol);
//                        parameters.put("interval", BinanceFrequency.getFrequency(f));
//                        parameters.put("limit", 500);
//
//                        try {
//                            String data = client.market().klines(parameters);
////                            log.error(data);
//                            return data;
//                        } catch (BinanceConnectorException e) {
//                            log.error(String.format("接口请求失败：【%s-%s】",symbol, f), e);
//                            log.error("fullErrMessage: {}", e.getMessage(), e);
//                        } catch (BinanceClientException e) {
//                            log.error(String.format("接口请求失败：【%s-%s】", symbol, f), e);
//                            log.error("fullErrMessage: {} \nerrMessage: {} \nerrCode: {} \nHTTPStatusCode: {}",
//                                    e.getMessage(), e.getErrMsg(), e.getErrorCode(), e.getHttpStatusCode(), e);
//                        }
//                        return null;
//                    });
//                    tasks.add(future);
//                }
//
//                long startTime = System.currentTimeMillis();
//                // 获取结果
//                for (int i = 0;i < needInitSymbols.size();i++) {
//                    Future<String> t = tasks.get(i);
//                    try {
//                        result.add(t.get());
//                    } catch (Exception e) {
//                        result.add(null);
//                        log.error(String.format("获取结果集失败：【%s-%s】", needInitSymbols.get(i), f), e);
//                    }
//                }
//
//                log.error("【{}】数据采集完成，目标数：{}，成功数：{}，失败数：{}，耗时：{}ms", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss,SSS"),
//                        needInitSymbols.size(),
//                        result.stream().map(Objects::nonNull).collect(Collectors.toList()).size(),
//                        needInitSymbols.size() - result.stream().map(Objects::isNull).collect(Collectors.toList()).size(),
//                        System.currentTimeMillis() - startTime);
//
//                startTime = System.currentTimeMillis();
//                // 保存并写入时间
//                for (int i = 0;i < needInitSymbols.size();i++) {
//                    String symbol = needInitSymbols.get(i);
//                    String key = String.format("binance:%s:%s:%s:%s", symbol, f, 3, 1);
//                    // OHLCV
//                    if (StringUtils.isBlank(result.get(i))) {
//                        continue;
//                    }
//                    List<Candlestick> candlesticks = (List<Candlestick>)binanceCandlestickParser.parse(result.get(i));
//                    FixedArrayList<Candlestick> bars = dbManager.getMdb().getBars(key);
//                    bars.addAll(candlesticks);
//                }
//                log.error("在【{}】写入mdb耗时：{}ms", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss,SSS"), System.currentTimeMillis() - startTime);
//                // 查大批量数据需要加大查询间隔，防止频率限制
//                needInitSymbols = getNeedInitSymbols(f);
//                try {
//                    Thread.sleep(65000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//        });
//        dbManager.setInited(true);
//    }


    private List<String> getNotLatestSymbols() {
        Map<String, Long> map = dbMapper.getTimeMap("1min");
        List<String> symbols = new ArrayList<>();
        Long today = DateUtil.today().getTime();
        map.forEach((key, value) -> {
            if (null != value && value >= today) {
                symbols.add(key);
            }
        });
        return symbols;
    }





//    @ApiOperation("增量更新")
//    @OuterResponseBody
//    @PostMapping("increment")
//    public void increment() {
//        log.info("K线增量更新开始....");
//
//        // 1.检查1分钟的时间，最新时间如果相差超过1天，则不进行爬取
//        List<String> symbols = getNotLatestSymbols();
//        List<Future<String>> tasks = new ArrayList<>();
//        List<String> result = new ArrayList<>();
//        if (binanceProperties.getUseProxy()) {
//            // 设置代理
//            ProxyInfo proxySetting = binanceProperties.getProxies().get(0);
//            Proxy proxyConn = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxySetting.getHost(), proxySetting.getPort()));
//            ProxyAuth proxy = new ProxyAuth(proxyConn, null);
//            client.setProxy(proxy);
//        }
//
//
//        // 创建任务
//        String f = "1min";
////        RMap<String, Long> minTimeMap = redissonClient.getMap(String.format(minTime, f));
//        Map<String,Long> minTimeMap = dbMapper.getTimeMap(f);
//        for (String symbol:symbols) {
//            Future<String> future = pool.submit(() -> {
//                LinkedHashMap<String, Object> parameters = new LinkedHashMap<>();
//                parameters.put("symbol", symbol);
//                parameters.put("interval", BinanceFrequency.getFrequency(f));
//                Long timestamp = minTimeMap.get(symbol);
//                parameters.put("startTime", timestamp);
////                log.error("最后时间" + timestamp);
//
//                try {
//                    String data = client.market().klines(parameters);
////                            log.error(data);
//                    return data;
//                } catch (BinanceConnectorException e) {
//                    log.error(String.format("接口请求失败：【%s-%s】",symbol, f), e);
//                    log.error("fullErrMessage: {}", e.getMessage(), e);
//                } catch (BinanceClientException e) {
//                    log.error(String.format("接口请求失败：【%s-%s】", symbol, f), e);
//                    log.error("fullErrMessage: {} \nerrMessage: {} \nerrCode: {} \nHTTPStatusCode: {}",
//                            e.getMessage(), e.getErrMsg(), e.getErrorCode(), e.getHttpStatusCode(), e);
//                }
//                return null;
//            });
//            tasks.add(future);
//        }
//
//        long startTime = System.currentTimeMillis();
//        // 获取结果
//        for (int i = 0;i < symbols.size();i++) {
//            Future<String> t = tasks.get(i);
//            try {
//                result.add(t.get());
//            } catch (Exception e) {
//                result.add(null);
//                log.error(String.format("采集失败：【%s-%s】", symbols.get(i), f), e);
//            }
//        }
//        log.error("【{}】数据采集完成，目标数：{}，成功数：{}，失败数：{}，耗时：{}ms", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss,SSS"),
//                symbols.size(),
//                result.stream().map(Objects::nonNull).collect(Collectors.toList()).size(),
//                symbols.size() - result.stream().map(Objects::isNull).collect(Collectors.toList()).size(),
//                System.currentTimeMillis() - startTime);
//
//        startTime = System.currentTimeMillis();
//        // 保存结果
//        for (int i = 0;i < symbols.size();i++) {
//            if (null == result.get(i)) {
//                continue;
//            }
//            String symbol = symbols.get(i);
//            String key = String.format("binance:%s:%s:%s:%s", symbol, f, 3, 1);
//            // 弹出最后一个时间bar,最后一根bar可能不是最新的数据
//            FixedArrayList<Candlestick> bars = dbManager.getMdb().getBarMap().get(key);
//            Candlestick lastBar = bars.removeTail();
//            if (null == lastBar) {
//                continue;
//            }
//            List<Candlestick> candlesticks = Candlestick.parseBinanceArray(result.get(i));
//            candlesticks = candlesticks.stream().filter(c -> c.getBarDate() >= lastBar.getBarDate()).collect(Collectors.toList());
//            bars.addAll(candlesticks);
//        }
//        log.error("在【{}】写入memory耗时：{}ms", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss,SSS"), System.currentTimeMillis() - startTime);
//        // 查大批量数据需要加大查询间隔，防止频率限制
////        try {
////            Thread.sleep(5000);
////        } catch (InterruptedException e) {
////            e.printStackTrace();
////        }
//    }





//    @ApiOperation("获取时间表2")
//    @OuterResponseBody
//    @GetMapping("getTimeMap2")
//    public Map<String,Long> getTimeMap2(String frequency) {
////        JSONObject time = JSON.parseObject(client.market().time());
////        Date dt = new Date(time.getLong("serverTime"));
////        System.out.println(DateFormatUtils.format(dt, "yyyy-MM-dd HH:mm:ss,SSS"));
//        dbManager.setInited(true);
//        return dbMapper.getTimeMap(frequency);
//    }


    @ApiOperation("K线")
    @OuterResponseBody
    @GetMapping("klines")
    public List<Candlestick> klines(String symbol,String frequency) {
        Long time = System.currentTimeMillis();
        String key = String.format(keyTemplate, symbol, frequency, 3, 1);
        List<Candlestick> result = dbManager.getMdb().getBarMap().get(key);
        if (CollectionUtils.isEmpty(result)) {
            return result;
        }
        int diff = result.size()-5;
        result = result.subList(diff >=0 ? diff : 0,result.size());
        log.error("klines，共{}条数据，耗时：{}ms",result.size(),System.currentTimeMillis() - time);
        return result;
    }


    public List<Candlestick> resample(List<Candlestick> originalData, long targetInterval) {
        List<Candlestick> resampledData = new ArrayList<>();

        // 计算目标间隔内的时间戳差值
        // 初始化目标时间戳
        long targetTimestamp = originalData.get(0).getBarDate();
        long endTime = originalData.get(originalData.size() - 1).getBarDate();

        while (targetTimestamp <= endTime) {
            // 在原始数据中找到在目标间隔内的所有蜡烛图数据
            List<Candlestick> candlesInInterval = new ArrayList<>();

            for (Candlestick candle : originalData) {
                if (candle.getBarDate() >= targetTimestamp && candle.getBarDate() < targetTimestamp + targetInterval) {
                    candlesInInterval.add(candle);
                }
            }

            // 如果存在蜡烛图数据，则计算目标间隔内的开盘价、最高价、最低价和收盘价，并添加到重新采样数据中
            if (!candlesInInterval.isEmpty()) {
                BigDecimal open = candlesInInterval.get(0).getOpen();
                BigDecimal high = BigDecimal.ZERO;
                BigDecimal low = BigDecimal.valueOf(Double.MAX_VALUE);
                BigDecimal close = candlesInInterval.get(candlesInInterval.size() - 1).getClose();
                BigDecimal volume = BigDecimal.ZERO;
                BigDecimal amount = BigDecimal.ZERO;

                for (Candlestick candle : candlesInInterval) {
                    high = high.max(candle.getHigh());
                    low = low.min(candle.getLow());
                    volume = volume.add(candle.getVolume());
                    amount = amount.add(candle.getAmount());
                }

                Candlestick resampledCandle = new Candlestick(targetTimestamp, open, high, low, close, volume, amount);
                resampledData.add(resampledCandle);
            }

            // 更新目标时间戳
            targetTimestamp += targetInterval;
        }

        return resampledData;
    }

    @ApiOperation("重新采样")
    @OuterResponseBody
    @GetMapping("resample")
    public List<Candlestick>  resample(String symbol, String frequency) {
        // OHLCV
        Long start = System.currentTimeMillis();
        String key = String.format(keyTemplate, symbol, "1min", 3, 1);
        // 取出最后一条数据
        Map<String, Long> timeMap = dbMapper.getTimeMap(frequency);
        if (timeMap.size() == 0) {
            return new ArrayList<>();
        }
        Long lastTime = timeMap.get(symbol);
        FixedArrayList<Candlestick> klines = dbManager.getMdb().getBarMap().get(key);
        if (CollectionUtils.isEmpty(klines)) {
            return new ArrayList<>();
        }
        List<Candlestick> mergeKlines = klines.stream().filter(k -> k.getBarDate() >= lastTime).collect(Collectors.toList());
        List<Candlestick> result = resample(mergeKlines, Frequency.getFrequencyUnit(frequency));
//        log.error("resample，共{}条数据，耗时：{}ms", result.size(),System.currentTimeMillis() - start);
        return result;
    }

    @ApiOperation("批量重新采样")
    @OuterResponseBody
    @GetMapping("batchResample")
    public List<Candlestick>  batchResample() {
        Long start = System.currentTimeMillis();
        List<Candlestick> result = new ArrayList<>();
        List<Future<Map<String, List<Candlestick>>>> tasks = new ArrayList<>();
        Arrays.stream(frequencys).forEach(f -> {
            if (f == "1min") {
                return;
            }
            tasks.add(pool.submit(() ->{
                Map<String, List<Candlestick>> single = new HashMap<>();
                dbManager.getMdb().getInstrumentMap().forEach((s, val) -> {
                    String smallKey = String.format(keyTemplate, val.getSymbol(), "1min", 3, 1);
                    String largeKey = String.format(keyTemplate, val.getSymbol(), f, 3, 1);
                    FixedArrayList<Candlestick> smallAll = dbManager.getMdb().getBarMap().get(smallKey);
                    FixedArrayList<Candlestick> largeAll = dbManager.getMdb().getBarMap().get(largeKey);
                    if (null == smallAll) {
                        dbManager.getMdb().getBarMap().put(smallKey, new FixedArrayList<>(FixedArrayList.MAX_SIZE));
                        return;
                    }
                    if (null == largeAll) {
                        dbManager.getMdb().getBarMap().put(largeKey, new FixedArrayList<>(FixedArrayList.MAX_SIZE));
                        return;
                    }
                    List<Candlestick> diff = resample(val.getSymbol(), f);
                    if (largeAll.size() == 0) {
                        largeAll.addAll(diff);
                        single.put(largeKey, diff);
                        return;
                    }
                    Candlestick last = largeAll.get(largeAll.size() - 1);
                    // 无增量不更新
                    if (CollectionUtils.isEmpty(diff)) {
                        return;
                    }
                    if (last.getBarDate() < diff.get(0).getBarDate()) {
                        log.error("无法更新最后一根K线[{}]，数据可能存在断层", DateFormatUtils.format(new Date(last.getBarDate()), "YYYY-MM-dd HH:mm:ss"));
                        largeAll.addAll(diff);
                        single.put(largeKey, diff);
                    }
                    if (last.getBarDate().equals(diff.get(0).getBarDate())) {
                        largeAll.removeTail();
                        largeAll.addAll(diff);
                        single.put(largeKey, diff);
                    }
                    if (last.getBarDate() > diff.get(0).getBarDate()) {
                        largeAll.removeTail();
                        largeAll.addAll(diff.stream().filter(c -> c.getBarDate() >= last.getBarDate()).collect(Collectors.toList()));
                        single.put(largeKey, diff);
                    }
                });
                return single;
            }));
        });

        tasks.forEach(t -> {
            try {
                t.get();
            } catch (Exception e) {
                log.error("批量重新采样失败", e);
            }
        });

        log.error("batchResample，共{}条数据，耗时：{}ms", result.size(),System.currentTimeMillis() - start);
        return result;
    }

    @ApiOperation("数据库重置")
    @OuterResponseBody
    @GetMapping("reset")
    public void reset() {
        dbManager.init();
    }


    @ApiOperation("异常测试")
    @OuterResponseBody
    @GetMapping("testException")
    public void testException() {
        int a = 0;
        assertThat(a).isEqualTo(0).thenThrow(BasicEcode.FAILED);
    }


    @Autowired
    private KlineSubscribeMessageHandler klineSubscribeMessageHandler;


    @ApiOperation("消息测试")
    @OuterResponseBody
    @GetMapping("testMessage")
    public void testMessage() {
        Map<String,FixedArrayList<Candlestick>> candlesticks = dbManager.getMdb().getBarMap();
        Map<String, List<Candlestick>> result = new HashMap<>();
        candlesticks.forEach((key, value) -> {
            if (key.contains("BTCUSDT") || key.contains("ETHUSDT")) {
                result.put(key, value.subList(value.size() - 1, value.size()));
            }
        });
        klineSubscribeMessageHandler.broadcast(result);
    }




    @ApiOperation("获取某个标的所有周期数据")
    @OuterResponseBody
    @GetMapping("listSymbolAll")
    public Map<String, FixedArrayList<Candlestick>> listSymbolAll(String symbol) {
        Map<String,FixedArrayList<Candlestick>> candlesticks = dbManager.getMdb().getBarMap();
        Map<String, FixedArrayList<Candlestick>> result = new HashMap<>();
        candlesticks.forEach((key, value) -> {
            String content = String.format(":%s:", symbol);
            if (key.contains(content)) {
                result.put(key, value);
            }
        });
        // 排序
        return result;
    }


    @ApiOperation("测试")
    @OuterResponseBody
    @GetMapping("listener")
    public void listener() {

        List<Candlestick> result = new ArrayList<>();
        List<Future<String>> tasks = new ArrayList<>();
        List<String> symbols = new ArrayList<>();
        symbols.add("BTCUSDT");
        symbols.add("NEARUSDT");
        symbols.add("ZRXUSDT");
        while (true) {
            result.clear();
            tasks.clear();
            Long start = System.currentTimeMillis();
            String time = client.market().time();
            Long serverTime = JSON.parseObject(time).getLong("serverTime");
            Long end = System.currentTimeMillis();
            log.error("本机时间：{}, 服务器时间：{}，差异：{}ms",
                    DateFormatUtils.format(new Date(serverTime), "yyyy-MM-dd HH:mm:ss,SSS"),
                    DateFormatUtils.format(new Date(end), "yyyy-MM-dd HH:mm:ss,SSS"),
                    end - serverTime);

            symbols.forEach(s -> {
                Future<String> future = pool.submit(() -> {
                    LinkedHashMap<String, Object> parameters = new LinkedHashMap<>();
                    parameters.put("symbol", s);
                    parameters.put("interval", "1m");
                    parameters.put("limit", 1);

                    try {
                        String data = client.market().klines(parameters);
                        return data;
                    } catch (BinanceConnectorException e) {
                        log.error(String.format("接口请求失败：【%s-%s】",s, "1m"), e);
                        log.error("fullErrMessage: {}", e.getMessage(), e);
                    } catch (BinanceClientException e) {
                        log.error(String.format("接口请求失败：【%s-%s】", s, "1m"), e);
                        log.error("fullErrMessage: {} \nerrMessage: {} \nerrCode: {} \nHTTPStatusCode: {}",
                                e.getMessage(), e.getErrMsg(), e.getErrorCode(), e.getHttpStatusCode(), e);
                    }
                    return null;
                });
                tasks.add(future);
            });
            tasks.forEach(t -> {
                try {
                    Long dt = JSON.parseArray(t.get()).getJSONArray(0).getLong(0);
                    log.error("K线时间：" + DateFormatUtils.format(dt, "yyyy-MM-dd HH:mm:ss,SSS"));
                }catch (Exception e) {
                    log.error("获取结果异常", e);
                }
            });
            log.error("请求耗时{}ms", System.currentTimeMillis() - start);


            try {
                Thread.sleep(1000);
            }catch (Exception e) {}

        }





    }

    @ApiOperation("上架测试")
    @OuterResponseBody
    @PostMapping("puton")
    public void putoff(@RequestBody List<String> symbols) {
        symbols.forEach(s -> {
            dbManager.getMdb().getInstrumentMap().remove(s);
            List<String> keys = dbManager.getMdb().getBarMap().keySet().stream().filter(k -> symbols.contains(k.split(":")[1])).collect(Collectors.toList());
            keys.forEach(k -> {
                dbManager.getMdb().getBarMap().remove(k);
            });
        });
    }

    @ApiOperation("下架测试")
    @OuterResponseBody
    @PostMapping("putoff")
    public void puton(@RequestBody List<String> symbols) {
        symbols.forEach(s -> {
          Instrument instrument = new Instrument();
          instrument.setSymbol(s);
          dbManager.getMdb().getInstrumentMap().put(s, instrument);
          String key = String.format(keyTemplate, s,ConstantItem.FREQUENCY_1MIN, ConstantItem.ADJUST_NO, ConstantItem.EXCHANGE_BINANCE);
          List<Candlestick> bars = dbManager.getMdb().getBars(key);
          Candlestick candlestick = new Candlestick();
          candlestick.setOpen(new BigDecimal(1));
          candlestick.setClose(new BigDecimal(1));
          candlestick.setHigh(new BigDecimal(1));
          candlestick.setLow(new BigDecimal(1));
          candlestick.setVolume(new BigDecimal(1));
          candlestick.setAmount(new BigDecimal(1));
          candlestick.setBarDate(new Date().getTime());
          bars.add(candlestick);
        });
    }




}
